package com.bonc.ioc.demo.utils;

import com.bonc.ioc.demo.exception.McpException;

import java.io.UnsupportedEncodingException;
import java.util.Base64;

/**
 * @projectName: sdvp
 * @description: Base64加解密
 * @author: Liyy
 * @create: 2020-08-21 15:06
 **/
public class Base64Util {
    final static Base64.Encoder ENCODER = Base64.getMimeEncoder();
    final static Base64.Decoder DECODER = Base64.getDecoder();

    /**
     * 给字符串加密
     * @param text
     * @return
     */
    public static String encode(String text) {
        byte[] textByte = new byte[0];
        try {
            textByte = text.getBytes("UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        String encodedText = ENCODER.encodeToString(textByte);
        return encodedText;
    }

    /**
     * 将加密后的字符串进行解密
     * @param encodedText
     * @return
     */
    public static String decode(String encodedText) {
        String text = null;

        if (encodedText == null) {
            return text;
        }

        try {
            text = new String(DECODER.decode(encodedText), "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }catch (IllegalArgumentException e) {
            e.printStackTrace();
            throw new McpException("密文格式异常"+encodedText);
        }
        return text;
    }

    /**
     * 将字符串转化为数组
     *
     * @author ycy
     * @date 2020/8/6 20:50
     * @param key
     * @return
     * @exception
     */
    public static byte[] decryptBase64(String key) {
        return Base64.getMimeDecoder().decode(key.getBytes());
    }

    /**
     * 将数组转化为字符创串
     *
     * @author ycy
     * @date 2020/8/6 20:50
     * @param bytes
     * @return
     * @exception
     */
    public static String encryptBase64(byte[] bytes) {
        return Base64.getEncoder().encodeToString(bytes);
    }

//    public static void main(String[] args) throws UnsupportedEncodingException {
////        String username = "Miracle Luna";
////        String password = "p@sSW0rd";
////        // 加密
////        System.out.println("====  [加密后] 用户名/密码  =====");
////        System.out.println(Base64Converter.encode(username));
////        System.out.println(Base64Converter.encode(password));
//        // 解密
//        System.out.println("\n====  [解密后] 用户名/密码  =====");
//        System.out.println(Base64Util.decode("azhTR3pRNFFEd2hNbHFPcE5xRlkrZz09"));
////        System.out.println(Base64Converter.decode(Base64Converter.encode(password)));
//    }


}
